<template>
  <div class="order-total">
    <!-- 头部 -->
    <div>
      <el-form inline>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="date"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- Echarts -->
    <!-- 方法一，使用v-if -->
    <!-- <chart-line
      v-if="Object.keys(chartData).length"
      :chart-data="chartData"
    ></chart-line> -->
    <!-- 方法二 ，在子组件中使用watch-->
    <chart-line :chart-data="chartData"></chart-line>
  </div>
</template>

<script>
import { api_order_ordertotal } from "@/apis/total";
import { formatYMDhms } from "@/filters/getTime";
import ChartLine from "@/components/ChartLine";
export default {
  components: {
    ChartLine,
  },
  data() {
    return {
      date: [],
      chartData: {},
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.getOrderData();
  },
  methods: {
    async getOrderData() {
      const res = await api_order_ordertotal({
        date: this.date ? JSON.stringify(this.date) : "[]",
      });

      //   处理Echarts数据
      let orderTime = [];
      let orderAmount = [];
      res.data.data.forEach((item) => {
        orderTime.push(formatYMDhms(item.orderTime, "YYYY-MM-DD"));
        orderAmount.push(item.orderAmount);
      });
      this.chartData = {
        orderTime,
        series: {
          data: orderAmount,
          type: "line",
          // smooth平滑性
          smooth: true,
          name: "订单数据",
        },
      };
     
    },

    // 查询
    handleQuery() {
      this.getOrderData();
    },
  },
};
</script>

<style lang="scss" scoped>
.order-total {
  width: 100%;
}
</style>
